﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace WeiXinUtils
{
    public class TemplateMsgData
    {
        public string value { get; set; }
        public string color { get; set; }

    }

    public class WeiXinTemplateMsg:WeiXinBase,IWeiXinMsg
    {
        public WeiXinTemplateMsg(string Appid, string Secret)
            : base(Appid, Secret)
        {
            this.data = new Dictionary<string, TemplateMsgData>();
        }
        public string template_id_short { get; set; }
        public string template_id 
        {
            get; 
            set; 
        }
        public string touser { get; set; }
        public string url { get; set; }
        public Dictionary<string,TemplateMsgData> data { get; set; }

        /// <summary>
        /// 获取模板ID
        /// </summary>
        /// <param name="template_id_short"></param>
        /// <returns></returns>
        public string GetTemplateIdByShortId(string template_id_short)
        {
                StringBuilder postData = new StringBuilder();
                postData.Append("{");
                postData.Append(string.Format("\"template_id_short\":\"{0}\"", template_id_short));
                postData.Append("}");
                string returnStr = HttpsUtils.Post(string.Format("https://api.weixin.qq.com/cgi-bin/template/api_add_template?access_token={0}", this.access_token), postData.ToString());
                dynamic returnData = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(returnStr);
                if (returnData.errcode == 0)
                {
                    return returnData.template_id;
                }
                else
                {
                    return string.Empty;
                }
        }

        /// <summary>
        /// 添加发送内容
        /// </summary>
        /// <param name="Keyword"></param>
        /// <param name="Content"></param>
        /// <param name="ColorStr"></param>
        public void AddContent(string Keyword,string Content,string ColorStr)
        {
            this.data.Add(Keyword, new TemplateMsgData() { value=Content, color=ColorStr });
        }

        /// <summary>
        /// 发送内容
        /// </summary>
        /// <param name="Msg"></param>
        /// <returns></returns>
        public string SendMsg()
        {
            string jsonStr= Newtonsoft.Json.JsonConvert.SerializeObject(this);
            return HttpsUtils.Post(string.Format("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={0}", this.access_token), jsonStr);
        }
    }
}